import React, {
    PureComponent
} from 'react';

import {
    Text,
    StyleSheet
} from 'react-native';

import {
    Actions
} from 'react-native-router-flux';

import {
    Press
} from './../../components';

import connect from './../../utils/connect';

import userAction from './../../state/actions/user';
import * as userTypes from './../../state/types/user';

interface Props {
    user?:any,
    onChange:Function
}

interface State {
    areaCode:string
}

@connect([`user`],{
    userActions:userAction
})
class AreaCode extends PureComponent<Props,State> {
    state = {
        areaCode:``
    }

    componentDidMount() {
        this._onChange();
        this.getAreaCode();
    }

    static defaultProps = {
        onChange:() => null
    }

    get userActions() {
        const {
            userActions
        } = this.props;
        return userActions;
    }

    get userState(): any {
        const {
            user
        } = this.props;
        return user;
    }

    get area() {
        const {
            area
        } = this.userState;
        return area || {};
    }

    get areaCode() {
        const {
            code
        } = this.area;
        const {
            areaCode
        } = this.state;
        return areaCode || code;
    }

    private getAreaCode = async () => {
        try {
            await this.userActions[
                userTypes.getCurrentAreaCode
            ]()
        }
        catch (e) {
            Tip.warm({
                message:e.message
            })
        }
        this._onChange()
    }

    private onChooseCode = () => {
        Actions.push(`/user/area`, {
            switchModal:true,
            onChange: this.onCodeChange
        })
    }

    private onCodeChange = ({code}) => {
        this.setState({
            areaCode: code
        },this._onChange)
    }

    private _onChange = () => {
        this.props.onChange(this.areaCode);
    }

    render() {
        return (
            <Press
                style={styles.container}
                onPress={this.onChooseCode}
            >
                <Text style={styles.text}>
                    {this.areaCode?`+${this.areaCode}`:`Choose`}
                </Text>
            </Press>
        )
    }
}

export default AreaCode;

const styles = StyleSheet.create({
    container: {
        height: `100%`,
        paddingRight: 16,
        alignItems: `center`,
        justifyContent: `center`
    },
    text: {
        fontSize: 16,
        color: `#fff`
    }
}) as any;